package com.ahy231.controller;

import com.ahy231.dto.*;
import com.ahy231.service.MessageService;
import io.swagger.annotations.*;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.web.bind.annotation.*;

/**
 * @author ahy231
 * @date 2021/7/28 13:41
 * @description
 */
@Api(tags = "聊天")
@RestController
@RequestMapping("/message")
public class MessageController {

    private final MessageService messageService;

    public MessageController(MessageService messageService) {
        this.messageService = messageService;
    }

    @ApiOperation("发送消息")
    @RequiresRoles("user")
    @PutMapping("/sendMessage")
    public Result sendMessage(@ApiParam("接收者id") @RequestParam Long userId, @ApiParam("消息内容") @RequestParam String message) {
        try {
            return new Result(ResultCode.SUCCESS, messageService.sendMessage(userId, message));
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(ResultCode.FAILED, e.getMessage());
        }
    }

    @ApiOperation("分页查看消息")
    @RequiresRoles("user")
    @PostMapping(value = "/getMessages", consumes = "application/x-www-form-urlencoded")
    public Result getMessages(@ApiParam("联系人 id") @RequestParam Long userId, @ApiParam("页号") @RequestParam Integer pageNum, @ApiParam("页面大小") @RequestParam Integer pageSize) {
        try {
            return new Result(ResultCode.SUCCESS, messageService.getMessages(userId, pageNum, pageSize));
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(ResultCode.FAILED, e.getMessage());
        }
    }

    @ApiOperation("设置消息已读")
    @RequiresRoles("user")
    @PostMapping(value = "/confirmMessage", consumes = {"application/x-www-form-urlencoded"})
    public Result confirmMessage(@ApiParam("消息 id") @RequestParam Long messageId) {
        try {
            return new Result(ResultCode.SUCCESS, messageService.confirmMessage(messageId));
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(ResultCode.FAILED, e.getMessage());
        }
    }

    @ApiOperation("所有联系人第一条消息")
    @RequiresRoles("user")
    @GetMapping("/firstMessages")
    public Result firstMessages(@ApiParam("页号") @RequestParam Integer pageNum,
                                @ApiParam("页面大小") @RequestParam Integer pageSize) {
        try {
            return new Result(ResultCode.SUCCESS, messageService.firstMessage(pageNum, pageSize));
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(ResultCode.FAILED, e.getMessage());
        }
    }
}
